<?php

/**
 * @package Framework03
 * @author Walter Tamboer
 */

/**
 * The singleton database helper which will return the active DatabaseConnection object.
 */
final class DB
{
	/**
	 * @var DatabaseConnection The instance of the active database connection.
	 */
	private static $Instance;
	/**
	 * Initializes a new instance of this class (which will never happen because this is a private constructor ;)).
	 */
	private function __construct()
	{
	}
	/**
	 * Gets the database connection.
	 * @return DatabaseConnection Returns the current active DatabaseConnection obejct.
	 */
	public static function Singleton()
	{
		if (!isset(self::$Instance))
		{
			$ClassName = Settings::Singleton()->Get('dbType') . 'Connection';

			$Filepath = 'api/' . $ClassName . '.php';

			if (!is_file($Filepath))
				throw new Exception("Trying to run database driver \"" . $ClassName . "\" that doesn't exist.");

			require_once($Filepath);

			if (!class_exists($ClassName))
				throw new Exception("Trying to run database driver \"" . $ClassName . "\" that doesn't exist.");
	
			self::$Instance = new $ClassName
				(
					Settings::Singleton()->Get('dbHost'),
					Settings::Singleton()->Get('dbUser'),
					Settings::Singleton()->Get('dbPass')
				);
			self::$Instance->Connect();
			self::$Instance->Select(Settings::Singleton()->Get('dbName'));
		}

		return self::$Instance;
	}
	/**
	 * Returns a prefixed table name.
	 * @param string $Name The name of the database table.
	 * @return string Returns the prefixed table name.
	 */
	public static function GetTable($Name)
	{
		try
		{
			return Settings::Singleton()->Get('dbTablePrefix') . $Name;
		}
		catch (Exception $E)
		{
			return $Name;
		}
	}
}

?>